#!/usr/bin/env python3
"""
AES解密验证脚本 - 验证生成的加密数据是否正确
"""
import json
import base64
import time
import sys

try:
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import unpad
except ImportError:
    print("❌ 缺少依赖包，请安装: pip install pycryptodome")
    sys.exit(1)

class EncryptionManager:
    def __init__(self, secret_key: str = "qwertyuiop1234567654zaqwsxcderfv"):
        self.secret_key = secret_key.encode('utf-8')[:32].ljust(32, b'\0')
    
    def aes_decrypt(self, encrypted_data: str) -> str:
        """AES256解密"""
        try:
            encrypted_bytes = base64.b64decode(encrypted_data)
            iv = encrypted_bytes[:16]
            encrypted = encrypted_bytes[16:]
            cipher = AES.new(self.secret_key, AES.MODE_CBC, iv)
            decrypted = unpad(cipher.decrypt(encrypted), AES.block_size)
            return decrypted.decode('utf-8')
        except Exception as e:
            raise ValueError(f"解密失败: {str(e)}")

def verify_encrypted_data(encrypted_data: str) -> dict:
    """验证加密数据"""
    try:
        encryption_manager = EncryptionManager()
        decrypted_json = encryption_manager.aes_decrypt(encrypted_data)
        decrypted_data = json.loads(decrypted_json)
        
        # 验证时间戳
        timestamp = decrypted_data.get("timestamp")
        if timestamp:
            current_time = int(time.time())
            time_diff = abs(current_time - timestamp)
            print(f"🕐 时间差: {time_diff}秒")
            if time_diff > 300:  # 5分钟
                print("⚠️ 请求已过期")
                return None
            else:
                print("✅ 时间戳有效")
        
        return decrypted_data
        
    except Exception as e:
        print(f"❌ 验证失败: {str(e)}")
        return None

def main():
    print("🔍 AES解密验证工具")
    print("=" * 50)
    
    # 刚才生成的加密数据
    test_encrypted = "NS5ovSnu8ZhdjsC5RL75AfYw6tVnZvoVrlud3YZK9H0HNOZgD3SyHbw3a0cOjlcdNQum4hLtfOwtn+iKdGd89PjiTKvZVJU1+OXB92s+ATnVeuExlJuGqE5rv5FJpeEb"
    
    print("📦 验证加密数据:")
    print(f"加密字符串: {test_encrypted[:50]}...")
    print()
    
    result = verify_encrypted_data(test_encrypted)
    if result:
        print("✅ 解密成功:")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        print()
        
        # 验证具体字段
        expected_phone = "18366542015"
        expected_code = "123456"
        
        if result.get("userPhone") == expected_phone:
            print(f"✅ userPhone验证通过: {expected_phone}")
        else:
            print(f"❌ userPhone验证失败: 期望{expected_phone}, 实际{result.get('userPhone')}")
            
        if result.get("userCode") == expected_code:
            print(f"✅ userCode验证通过: {expected_code}")
        else:
            print(f"❌ userCode验证失败: 期望{expected_code}, 实际{result.get('userCode')}")
            
    else:
        print("❌ 解密失败")

if __name__ == "__main__":
    main()
